﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using yafc.SessionLayer;
using System.Threading;

namespace yafc
{
	class UpdateThread
	{
		#region Fields

		public delegate void Callback();

		private Callback callback;
		private Session session;
		private ManualResetEvent signalExit;
		private ManualResetEvent signalExited = new ManualResetEvent(false);

		private Queue<string> postBuffer = new Queue<string>();

		#endregion

		#region Public Properties

		public ManualResetEvent SignalExited
		{
			get
				{ return signalExited; }
		}

		#endregion

		#region Constructors

		public UpdateThread(Session Sess, Callback Cb, ManualResetEvent SignalExit)
		{
			session = Sess;
			callback = Cb;
			signalExit = SignalExit;
		}

		#endregion

		#region Public Methods

		public void run()
		{
			while (true)
			{
				doOnePost();
				updateFrndTL();

				if (signalExit.WaitOne(0, true))
				{
					break;
				}

				callback.Invoke();

				Thread.Sleep(10000);
			}

			signalExited.Set();
		}

		public void post(string Msg)
		{
			lock(postBuffer)
			{
				postBuffer.Enqueue(Msg);
			}
		}

		#endregion

		#region Non-Public Methods

		private void updateFrndTL()
		{
			session.updateFrndTL();
		}

		private void doOnePost()
		{
			string msg;
			lock(postBuffer)
			{
				if (postBuffer.Count == 0)
					return;
				msg = postBuffer.Dequeue();
			}

			session.post(msg);
		}

		#endregion
	}
}
